package com.tjetc.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tjetc.domain.ChatHistory;
import jakarta.websocket.EncodeException;
import jakarta.websocket.Encoder;
import jakarta.websocket.EndpointConfig;

public class ChatHistoryEncoder implements Encoder.Text<ChatHistory> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String encode(ChatHistory chatHistory) throws EncodeException {
        try {
            // 将ChatHistory转换为ObjectNode以便修改
            ObjectNode jsonNode = objectMapper.valueToTree(chatHistory);
            
            // 如果date字段存在，添加time字段（时间戳）
            if (chatHistory.getDate() != null) {
                jsonNode.put("time", chatHistory.getDate().getTime());
            }
            
            return objectMapper.writeValueAsString(jsonNode);
        } catch (Exception e) {
            throw new EncodeException("Failed to encode ChatHistory to JSON", e.getMessage());
        }
    }

    @Override
    public void init(EndpointConfig config) {
        // 可选初始化
    }

    @Override
    public void destroy() {
        // 可选清理
    }
}
